package com.momo.seckilling.EventModel;


import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * Created by li on 2019/3/18.
 */
public class CentralEventProcessor{
    public Map<Class,Handle> forwardings = new HashMap<Class,Handle>();//转发器
    public BlockingDeque<Event> centralQueue = new LinkedBlockingDeque<Event>();//中央处理队列
    public CentralForwarding centralForwarding = new CentralForwarding();
    public EventProcess eventProcess = new EventProcess();
    public CentralEventProcessor(){
        SeckillEventProcessor seckillEventProcessor = new SeckillEventProcessor(this);
        forwardings.put(SeckillEvent.class,seckillEventProcessor);
        CentralForwarding centralForwardingHandle = new CentralForwarding();
        forwardings.put(CentralForwardingEvent.class,centralForwardingHandle);
        OrderEventProcessor orderEventProcessor = new OrderEventProcessor(this);
        forwardings.put(OrderEvent.class,orderEventProcessor);
        new Thread(eventProcess).start();
    }

    public void processEvent(Event event){
        centralForwarding.handle(event);
    }

    class CentralForwarding implements Handle{
        @Override
        public void handle(Event event) {
            try {
                centralQueue.put(event);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    class EventProcess extends Thread{

        @Override
        public void run() {
            while(true){
                try {
                    Event event = centralQueue.take();
                    Class enventclass = event.getClass();
                    Handle handle = forwardings.get(enventclass);
                    handle.handle(event);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        CentralEventProcessor centralEventProcessor = new CentralEventProcessor();
        SeckillEvent newSeckillEvent = new SeckillEvent("new",SeckillEventType.NEW,null,0,0);
        centralEventProcessor.processEvent(newSeckillEvent);
    }
}
